import router from '@/router';
import smCrypto from 'sm-crypto';
// import JSEncrypt from 'jsencrypt';

// 根据子属性查找所有关联的层数
export const findPatentValue = (array: [], value: any, valueName = 'value', childrenName = 'children') => {
  if (!value || !Array.isArray(array)) {
    return [];
  }
  const result: any[] = [];
  let valid = false;
  const seek = (array: [], value: any) => {
    let parentValue: any = null;
    const up = (array: [], value: any, lastValue: any = '') => {
      array.forEach(v => {
        const val = v[valueName];
        const child: [] = v[childrenName];
        if (val === value) {
          valid = true;
          parentValue = lastValue;
          return;
        }
        if (child && child.length) {
          up(child, value, val);
        }
      });
    };
    up(array, value);
    if (parentValue) {
      result.unshift(parentValue);
      seek(array, parentValue);
    }
  };
  seek(array, value);
  return valid ? [...result, value] : [];
};

// 根据子属性查找所有关联的属性
export const findPatentMap = (array: [], value: any, valueName = 'value', childrenName = 'children', labelKey = '') => {
  if (!value || !Array.isArray(array)) {
    return [];
  }
  const result: any[] = [];
  let valid = false;
  const seek = (array: [], value: any) => {
    let parentValue: any = null;
    let labelName: any = null;
    const up = (array: [], value: any, lastValue: any = '') => {
      array.forEach(v => {
        const val = v[valueName];
        const child: [] = v[childrenName];
        if (val === value) {
          valid = true;
          parentValue = lastValue;
          labelName = v[labelKey] || v;
          return;
        }
        if (child && child.length) {
          up(child, value, val);
        }
      });
    };
    up(array, value);
    if (labelName) {
      result.unshift(labelName);
      seek(array, parentValue);
    }
  };
  seek(array, value);
  return valid ? [...result] : [];
};

// 防抖函数
export const debounce = (fn: any, delay: number) => {
  let timer: any = null;
  return function (...args) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
};

// 节流函数
export const throttle = (fn: any, delay: number) => {
  let timer: any = null;
  let status = false;
  return function (...args) {
    if (timer) {
      return;
    }
    if (!status) {
      status = true;
      fn.apply(this, args);
    }
    timer = setTimeout(() => {
      if (status) {
        fn.apply(this, args);
        timer = null;
      }
    }, delay);
  };
};

export const filedArrJoin = (dataArr = [], name: string, value: string) => {
  const datas: any = dataArr.map((o: any) => ({
    label: o[name],
    value: o[value],
  }));
  datas.unshift({ label: '全部', value: '' });
  return datas;
};

export const cacheRouter = (params: any) => {
  const routerStr = Object.keys(params)
    .map(key => `${key}=${params[key]}`)
    .join('&');
  if (routerStr) {
    router.replace({
      path: router.currentRoute.value.path,
      query: params,
    });
  }
};

export const getArrayLabel = (arr: any, value: any, filedObj: any) => {
  if (arr) {
    const resultFiled = Object.assign({ label: 'label', value: 'value' }, filedObj);
    const obj = arr.find((o: any) => o[resultFiled.value] == value);
    return obj ? obj[resultFiled.label] : '';
  }
};

/**
 * 处理千分位 + 单位
 * @param value 值
 * @param length 小数点后几位
 * @param nullValue 空值替换符号
 * @param symbolValue 千分位符号
 * @returns {string}
 */
export function numberUnit(value: any, length: any = 2, nullValue: any = '--', symbolValue: any = ',') {
  const replace = /\B(?=(\d{3})+(?!\d))/g;
  let num: any = '';
  let unit: any = '';
  if (!value || value === 'null' || value === 'undefined') {
    return nullValue;
  }
  num = Number(value);
  if (num > 10000 && num < 100000000) {
    unit = '万';
    num = num / 10000;
  }
  if (num >= 100000000) {
    unit = '亿';
    num = num / 100000000;
  }
  num = num.toFixed(length);

  const strNum = String(num).split('.');
  if (strNum[1] !== '00') {
    const decimalsNum = strNum[1].split('');
    return `${strNum[0].replace(replace, symbolValue)}.${decimalsNum[1] === '0' ? decimalsNum[0] : strNum[1]}` + unit;
  } else {
    return `${strNum[0].replace(replace, symbolValue)}${unit}`;
  }
}

export const getArrayObj = (arr: any, value: any) => {
  if (arr) {
    // 比较值
    let obj = arr.find((o: any) => o.value == value);
    if (obj) {
      return obj;
    }
    // 比较名称（后台可能直接返回中文的情况）
    obj = arr.find((o: any) => o.label == value);
    return obj;
  }
};

export function doEncrypt(msgString: string, publicKey: string) {
  let msg = msgString;
  if (typeof msgString !== 'string') {
    msg = JSON.stringify(msgString);
  }
  const sm2 = smCrypto.sm2;
  const cipherMode = 1; // 特别注意,此处前后端需保持一致
  // const publicKey2 = '04bbfbea94e01445784544b29b9430a7b5309d6c93d0a05df2bfd43497f7f8de20cce0bf934f69e90ea399b372865899506a0abccd23a660dd191480014f2857cf';
  // 加密结果
  const encryptData = sm2.doEncrypt(msg, publicKey, cipherMode);
  // 加密后的密文前需要添加04，后端才能正常解密
  return '04' + encryptData;
}

// export const commonEncrypt = (value: any) => {
//   const encryptor = new JSEncrypt();
//   encryptor.setPublicKey(
//     '-----BEGIN PUBLIC KEY-----MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJPXoncPIK+pvTzNIlAIcL1nhOL42XkOwXDu9Y+fvZbGsT1VhKdLMpDQa34/JvrUx9gV2OBBAO/TyXxsZCMl2MUCAwEAAQ==-----END PUBLIC KEY-----',
//   );
//   return encryptor.encrypt(value);
// };

// export function commonDecrypt(msg: any) {
//   const decrypt = new JSEncrypt();
//   decrypt.setPrivateKey(
//     '-----BEGIN RSA PRIVATE KEY-----MIIBOwIBAAJBAJPXoncPIK+pvTzNIlAIcL1nhOL42XkOwXDu9Y+fvZbGsT1VhKdLMpDQa34/JvrUx9gV2OBBAO/TyXxsZCMl2MUCAwEAAQJATx/SWMwk3z8GA7t6CMFrrULxERTEN5EZIJsTm6mPq1ibNx9TZbOtbmfd6NKqyCtaKP1RNSbyXA4lfWnBssS9ZQIhAOI9UerijpQA431m+ODrts5++hAcUU8Gu0QGQTQNq/bPAiEAp0pEO9H0P6oj23tMWVm+qJnFY4Pf/elL5HxipkCfXCsCIGRc0YdCg/+SOVj7IjMdPhZy69nTxhopoU92+tvtqLivAiEAmUIokMUgBtNQVlr270SQrtVxSGIgavW4WXK6zaSWWlECIQCjY/U9/mDsCgvTRrpfpOvxYQZQBSj0ninI4qfvKaV5Tg==-----END RSA PRIVATE KEY-----',
//   );
//   const decryptMsg = decrypt.decrypt(msg);
//   return decryptMsg;
// }

export const getImageUrl = (name: string, type: string) => {
  return new URL(`../assets/images/${name}.${type}`, import.meta.url).href;
};

export function flatArray(multiArr: any[]) {
  const arr: any[] = [];
  const multiArrFn = (changeArr: any[], key = 'children') => {
    for (let i = 0; i < changeArr.length; i++) {
      const item = Object.assign({}, changeArr[i]);
      delete item[key];
      arr.push(item);
      console.log('arr', arr);

      if (changeArr[i][key] && changeArr[i][key].length) {
        multiArrFn(changeArr[i][key]);
      }
    }
  };
  multiArrFn(multiArr);
  return arr;
}

export const withInstall = <T>(component: T, alias?: string) => {
  const comp = component as any;
  comp.install = (app: any) => {
    app.component(comp.name || comp.displayName, component);
    if (alias) {
      app.config.globalProperties[alias] = component;
    }
  };
  return component;
};
export const getFileIconByType = (type: any, resourceExtension: string) => {
  let iconStr = '';
  switch (type) {
    case '0':
      iconStr = 'icon-icon_folder';
      break;
    case '1':
      iconStr = 'icon-icon_picture';
      break;
    case '2':
      iconStr = 'icon-icon_video';
      break;
    case '3':
      // const fileType = fileName.split('.')[1];
      if (['doc', 'docx'].includes(resourceExtension)) {
        iconStr = 'icon-icon_word';
      } else if (resourceExtension === 'pdf') {
        iconStr = 'icon-icon_pdf';
      } else if (['ppt', 'pptx'].includes(resourceExtension)) {
        iconStr = 'icon-icon_ppt';
      } else if (resourceExtension === 'zip') {
        iconStr = 'icon-icon_zip';
      } else if (['xls', 'xlsx'].includes(resourceExtension)) {
        iconStr = 'icon-icon_xls';
      } else if (['txt'].includes(resourceExtension)) {
        iconStr = 'icon-icon_txt';
      } else {
        iconStr = 'icon-icon_unknown';
      }
      break;
    case '4':
      iconStr = 'icon-icon_audio';
      break;
    case '5':
      iconStr = 'icon-icon_unknown';
      break;
  }
  return iconStr;
};
export const handleTree = tree => {
  return tree.map(t => {
    return {
      title: t.name,
      value: t.id,
      children: handleTree(t.children),
    };
  });
};
export const sizeTostr = size => {
  let data = '';
  if (size < 0.1 * 1024) {
    // 如果小于0.1KB转化成B
    data = size.toFixed(2) + 'B';
  } else if (size < 0.1 * 1024 * 1024) {
    // 如果小于0.1MB转化成KB
    data = (size / 1024).toFixed(2) + 'KB';
  } else if (size < 0.1 * 1024 * 1024 * 1024) {
    // 如果小于0.1GB转化成MB
    data = (size / (1024 * 1024)).toFixed(2) + 'MB';
  } else {
    // 其他转化成GB
    data = (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB';
  }
  const sizestr = data + '';
  const len = sizestr.indexOf('.');
  const dec = sizestr.substr(len + 1, 2);
  if (dec == '00') {
    // 当小数点后为00时 去掉小数部分
    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
  }
  return sizestr;
};

// 获取图片像素
export const getImgPixel = (src: string) => {
  console.log('src', src);

  const image = new Image();
  let imgPixel: any = {};
  image.src = src;
  return new Promise(resolve => {
    image.onload = () => {
      imgPixel = {
        width: image.width,
        height: image.height,
      };
      resolve(`${imgPixel.width} × ${imgPixel.height}`);
    };
  });
};
export const getFormatTime = duration => {
  const hh = Math.floor(duration / 3600) < 10 ? '0' + Math.floor(duration / 3600) : Math.floor(duration / 3600);
  const mm =
    Math.floor((duration % 3600) / 60) < 10
      ? '0' + Math.floor((duration % 3600) / 60)
      : Math.floor((duration % 3600) / 60);
  const ss = Math.floor(duration % 60) < 10 ? '0' + Math.floor(duration % 60) : Math.floor(duration % 60);
  return `${hh}:${mm}:${ss}`;
};
// 获取视频像素
export const getVideoParameter = () => {
  const video: any = document.getElementById('video');
  return new Promise(resolve => {
    video.oncanplay = function () {
      console.log('video', video);
      getFormatTime(video.duration);
      resolve({
        pixel: `${video.videoWidth} × ${video.videoHeight}`,
        formatDur: getFormatTime(video.duration),
      });
    };
  });
};
// base64转blob对象
export const dataURLtoBlob = dataurl => {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
};
// 将blob转换为file
export const blobToFile = (theBlob, fileName) => {
  theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
  theBlob.name = fileName; // 文件名
  return new File([theBlob], fileName, { type: theBlob.type, lastModified: Date.now() });
};
// 生成唯一ID
export const createUuid = () => {
  const abc = [
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
    'g',
    'h',
    'i',
    'g',
    'k',
    'l',
    'm',
    'n',
    'o',
    'p',
    'q',
    'r',
    's',
    't',
    'u',
    'v',
    'w',
    'x',
    'y',
    'z',
  ];
  const [max, min] = [Math.floor(Math.random() * (10 - 7 + 1) + 1), Math.floor(Math.random() * (17 - 10 + 1) + 17)];
  const str = abc
    .sort(() => 0.4 - Math.random())
    .slice(max, min)
    .slice(0, 8)
    .join('');
  const uuid = new Date().getTime() + str;
  return uuid;
};

export const byteLength = str => {
  let length = 0;
  Array.from(str).map((char: any) => {
    if (char.charCodeAt(0) > 255) {
      // 字符编码大于255，说明是双字节字符
      length += 2;
    } else {
      length++;
    }
  });

  return length;
};

// export const getAssetsImageUrl = (url: string) => {
//   return new URL(`../assets/${url}`, import.meta.url).href;
// };

export const getFileTypeIcon = fileName => {
  let iconStr = '';
  const index = fileName.lastIndexOf('.');
  // 获取后缀
  const type = fileName.substring(index + 1);
  if (['doc', 'docx', 'DOC', 'DOCX'].includes(type)) {
    iconStr = 'icon-icon_word';
  } else if (['pdf', 'PDF'].includes(type)) {
    iconStr = 'icon-icon_pdf';
  } else if (['ppt', 'pptx', 'PPT', 'PPTX'].includes(type)) {
    iconStr = 'icon-icon_ppt';
  } else if (['zip', 'ZIP', 'rar', 'RAR'].includes(type)) {
    iconStr = 'icon-icon_zip';
  } else if (['xls', 'xlsx', 'XLS', 'XLSX'].includes(type)) {
    iconStr = 'icon-icon_xls';
  } else if (['txt', 'TXT'].includes(type)) {
    iconStr = 'icon-icon_txt';
  } else if (['mp3', 'wav', 'MP3', 'WAV'].includes(type)) {
    iconStr = 'icon-icon_audio';
  } else if (
    [
      'mov',
      'avi',
      'flv',
      'vob',
      'wmv',
      'mp4',
      '3gp',
      'rmvb',
      'mvb',
      'mkv',
      'MOV',
      'AVI',
      'FLV',
      'VOB',
      'WMV',
      'MP4',
      '3GP',
      'RMVB',
      'MVB',
      'MKV',
    ].includes(type)
  ) {
    iconStr = 'icon-icon_video';
  } else {
    iconStr = 'icon-icon_unknown';
  }
  return iconStr;
};

export const imageAccept =
  'image/xbm,image/tif,image/pjp,image/apng,image/svgz,image/jpg,image/jpeg,image/ico,image/tif,image/gif,image/svg,image/jff,image/webp,image/png,image/bmp,image/pjpeg,image/avif';
export const videoAccept = [
  'mov',
  'avi',
  'flv',
  'vob',
  'wmv',
  'mp4',
  '3gp',
  'rmvb',
  'mvb',
  'mkv',
  'MOV',
  'AVI',
  'FLV',
  'VOB',
  'WMV',
  'MP4',
  '3GP',
  'RMVB',
  'MVB',
  'MKV',
];
export const audioAccept = ['mp3', 'wav', 'MP3', 'WAV'];
